package com.ibangnuo.manage.service.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.ibangnuo.framework.domain.*;

import com.ibangnuo.framework.domain.request.alipay.FreezingFundRequest;
import com.ibangnuo.framework.domain.request.alipay.PayRequest;
import com.ibangnuo.framework.domain.request.alipay.PreCreateRequest;
import com.ibangnuo.framework.domain.request.alipay.RefundRequest;
import com.ibangnuo.framework.domain.request.wxpay.WxpayDomainRequest;
import com.ibangnuo.framework.domain.response.alipay.PayCode;
import com.ibangnuo.framework.exception.ExceptionCast;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.model.response.ResponseResult;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;

import com.ibangnuo.manage.dao.OrderDetailsRepository;
import com.ibangnuo.manage.dao.OrderRepository;
import com.ibangnuo.manage.dao.alipay.PayRepository;
import com.ibangnuo.manage.dao.alipay.RefundRepository;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.dao.terminal.TerminalRepository;
import com.ibangnuo.manage.dao.wxpay.CommercialTenantDetailsWxMapper;
import com.ibangnuo.manage.dao.wxpay.CommercialTenantDetailsWxRepository;
import com.ibangnuo.manage.service.wxpay.WxpayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author: wwy
 * @Date: 2019-12-19 16:17
 */
@Service
public class PayService {

    private static Logger LOGGER = LoggerFactory.getLogger(PayService.class);
    @Value("${app_id}")
    private String appId;

    @Value("${key.private_key}")
    private String privateKey;

    @Value("${key.alipay_public_key}")
    private String alipayPublicKey;

    @Value("${gateway}")
    private String gateway;

    @Value("${third.app_id}")
    private String thirdAppId;

    @Value("${third.key.private_key}")
    private String thirdPrivateKey;

    @Value("${third.key.alipay_public_key}")
    private String thirdAlipayPublicKey;

    @Value("${third.gateway}")
    private String thirdGateway;

    @Value("${third.query.pollingCount}")
    private Integer pollingCount;

    @Value("${third.query.pollingMilliseconds}")
    private Long pollingMilliseconds;

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderDetailsRepository orderDetailsRepository;
    @Autowired
    private RefundRepository refundRepository;
    @Autowired
    private PayRepository payRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private TerminalRepository terminalRepository;
    @Autowired
    private CommercialTenantDetailsWxMapper commercialTenantDetailsWxMapper;
    @Autowired
    private CommercialTenantDetailsWxRepository commercialTenantDetailsWxRepository;
    @Autowired
    private WxpayService wxpayService;
    private static List<String> list;
    static {
        list = new ArrayList<>();
        list.add("10");
        list.add("11");
        list.add("12");
        list.add("13");
        list.add("14");
        list.add("15");
    }

    /**
     * 支付流程代码
     * 1.微信支付
     * 2.支付宝支付
     *
     * @param payRequest
     * @return
     */
    public ObjectResult pay(PayRequest payRequest) {
        String code = payRequest.getAuthCode().substring(0, 2);
        ObjectResult objectResult = null;
        if (list.contains(code)) {//微信
            WxpayDomainRequest wxpayDomainRequest = new WxpayDomainRequest();
            wxpayDomainRequest.setBody(payRequest.getSubject());
            wxpayDomainRequest.setAuthCode(payRequest.getAuthCode());
            wxpayDomainRequest.setDeviceSn(payRequest.getDeviceSn());
//            wxpayDomainRequest.setMchId();
            wxpayDomainRequest.setPayType(payRequest.getCodeType());
            wxpayDomainRequest.setWaterNote(payRequest.getWaterNote());
            wxpayDomainRequest.setTotalFee(payRequest.getTotalAmount());
            objectResult = wxpayService.pay(wxpayDomainRequest);
        }
        if ("28".equals(code)) {//支付宝
            objectResult = Alipay(payRequest);
        }
        return objectResult;
    }


    /**
     * 支付流程代码
     * 1.校验参数合法性
     * 2.保存订单(待支付)
     * 3.调用支付接口
     * 4.修改订单状态
     *
     * @param payRequest
     * @return
     */
    public ObjectResult Alipay(PayRequest payRequest) {
        if (payRequest == null) {
            return new ObjectResult(CommonCode.INVALID_PARAM, null);
        }
        if (StringUtils.isEmpty(payRequest.getAuthCode())) {
            return new ObjectResult(CommonCode.INVALID_PARAM, null);
        }
        //查询门店
        Terminal terminal = terminalRepository.findBySn(payRequest.getDeviceSn());
        String shopId = terminal.getShopId();//门店id
        Order order = new Order();
        order.setCreateTime(new Date());
        if (StringUtils.isNotEmpty(payRequest.getSellerId())) {
            CommercialTenant bySellerId = commercialRepository.findByPId(payRequest.getSellerId());
            order.setCommercialTenantId(bySellerId.getId());//所属商户

        }
        order.setShopId(shopId);
        //order.setActualPayment();//实收金额
        order.setConsumeMoney(Integer.parseInt(new DecimalFormat("0").format(payRequest.getTotalAmount() * 100)));//订单金额
        order.setNote(payRequest.getWaterNote());//订单备注
        order.setStatus(0);//待支付
        order.setPayType(payRequest.getCodeType());//支付方式
        order.setPayWay(0);
        order.setSn(payRequest.getDeviceSn());//机具sn
        Terminal order1 = terminalRepository.findBySn(payRequest.getDeviceSn());
        if (order1 != null) {
            order.setShopId(order1.getShopId());
        }
        Order save = orderRepository.save(order);
        AlipayTradePayResponse response = this.payResult(payRequest.getAuthCode(), payRequest.getSubject(), payRequest.getTotalAmount(), payRequest.getSellerId());
        Order one = this.getById(save.getId());
        if (one == null) {
            return new ObjectResult(PayCode.PAY_ORDER_NOTEXISTS, null);
        }
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.setCreateTime(new Date());
        String responseStrJson = JSONObject.toJSONString(response);
        Pay pay = new Pay();
        if (response != null) {
            if (response.isSuccess() && "10000".equals(response.getCode())) {
                String receiptAmount = response.getReceiptAmount();//实际付款金额
                one.setActualPayment(Integer.parseInt(new DecimalFormat("0").format((Double.parseDouble(receiptAmount) * 100))));
                one.setSerialNumber(response.getTradeNo());//流水号
                one.setOutTradeNo(response.getOutTradeNo());//商家订单号
                one.setStatus(1);
                Order save1 = orderRepository.save(one);
                orderDetails.setOrderId(save1.getId());
                orderDetails.setContent(responseStrJson);
                orderDetailsRepository.save(orderDetails);
                pay.setCreateTime(new Date());
                pay.setDescribe("支付成功");
                pay.setMoney(Integer.parseInt(new DecimalFormat("0").format((Double.parseDouble(receiptAmount) * 100))));
                pay.setOrderId(save1.getId());
                pay.setStatus(1);
                payRepository.save(pay);
                Map<String, Object> map = new HashMap<>();
                map.put("outOrderId", response.getOutTradeNo());
                return new ObjectResult(PayCode.PAY_SUCCESS, map);
            }
        }
        pay.setOrderId(one.getId());
        pay.setStatus(0);
        pay.setMoney(one.getActualPayment());
        pay.setDescribe("支付失败");
        one.setStatus(2);
        Order save1 = orderRepository.save(one);

        orderDetails.setOrderId(save1.getId());
        orderDetails.setContent(responseStrJson);
        orderDetailsRepository.save(orderDetails);
        pay.setCreateTime(new Date());
        payRepository.save(pay);
        return new ObjectResult(PayCode.PAY_FILL, null);
    }


    /**
     * 退款流程
     * 1.初始化退款
     * 2.进行退款
     * 3.更改退款状态
     *
     * @return
     */
    public ResponseResult refund(RefundRequest refundRequest) {
        Order byOutTradeNo = orderRepository.findByOutTradeNo(refundRequest.getOutTradeNo());
        ResponseResult responseResult=null;
        if (byOutTradeNo != null) {
            Integer payWay = byOutTradeNo.getPayWay();
            if (payWay == 0) {//支付宝
                 responseResult = this.AliPayRefund(refundRequest);
            }
            if (payWay == 1) {//微信
//                wxpayService.
            }
        }
        return responseResult;
//        return null;
    }


    /**
     * 退款流程
     * 1.初始化退款
     * 2.进行退款
     * 3.更改退款状态
     *
     * @return
     */
    public ResponseResult AliPayRefund(RefundRequest refundRequest) {
        Refund refund = new Refund();
        refund.setStatus(0);
        refund.setRefundFee(Integer.parseInt(new DecimalFormat("0").format(refundRequest.getRefundAmount() * 100)));//退款金额
        refund.setSn(refundRequest.getSnNum());//设备sn号
        refund.setCreateTime(new Date());
        Refund save = refundRepository.save(refund);
        AlipayTradeRefundResponse response = this.refundResult(refundRequest.getTradeNo(), refundRequest.getRefundAmount());
        if (response != null) {
            save.setBuyeUserId(response.getBuyerUserId());
            save.setOutTradeNo(response.getOutTradeNo());
            save.setTradeNo(response.getTradeNo());
            if (response.isSuccess() && "10000".equals(response.getCode())) {
                save.setStatus(1);
                save.setRefundFee(Integer.parseInt(new DecimalFormat("0").format(refundRequest.getRefundAmount() * 100)));
                Order order = orderRepository.findByOutTradeNo(response.getOutTradeNo());//外部订单号
                order.setStatus(3);//退款
                save.setPayType(order.getPayType());
                save.setDescribe("退款成功");
                orderRepository.save(order);
                refundRepository.save(save);
                return new ResponseResult(PayCode.REFUND_SUCCESS);
            } else {
                save.setStatus(2);
            }
        } else {
            save.setStatus(2);
        }
        save.setDescribe("退款失败");
        refundRepository.save(save);
        return new ResponseResult(PayCode.REFUND_FILL);
    }

    /**
     * 退款接口调用
     *
     * @param tradeNo
     * @param refundAmount
     * @return
     */
    private AlipayTradeRefundResponse refundResult(String tradeNo, Double refundAmount) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("trade_no", tradeNo);
        map.put("refund_amount", refundAmount);
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            return response;
        } catch (AlipayApiException e) {
            LOGGER.error("退款异常{}", e.getMessage());
        }
        return response;

    }

    /**
     * 支付接口调用
     *
     * @param authCode    支付授权码
     * @param subject     订单主题
     * @param totalAmount 总金额
     * @param sellerId    商户id
     * @return
     */
    private AlipayTradePayResponse payResult(String authCode, String subject, Double totalAmount, String sellerId) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", PrimaryKeyUtil.nextId() + "");
        map.put("scene", "bar_code");
        map.put("auth_code", authCode);
        map.put("subject", subject);
        map.put("total_amount", totalAmount);
        map.put("seller_id", sellerId);
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        AlipayTradePayResponse response = null;
        try {
            response = alipayClient.execute(request);
            return response;
        } catch (AlipayApiException e) {
            LOGGER.error("支付异常{}", e.getMessage());
        }
        return null;
    }

    /**
     * 预创建订单
     *
     * @param preCreateRequest
     * @return
     */
    public ObjectResult preCreate(PreCreateRequest preCreateRequest) {
        if (preCreateRequest == null) {
            return new ObjectResult(CommonCode.INVALID_PARAM, null);
        }
        Order order = new Order();
        if (StringUtils.isNotEmpty(preCreateRequest.getPId())) {
            CommercialTenant bySellerId = commercialRepository.findByPId(preCreateRequest.getPId());
            order.setCommercialTenantId(bySellerId.getId());//所属商户
        }
        order.setCreateTime(new Date());
        CommercialTenant commercialTenant = commercialRepository.findByPId(preCreateRequest.getPId());
        if (commercialTenant != null) {
            order.setCommercialTenantId(commercialTenant.getId());//所属商户
        }
        //order.setActualPayment(Integer.parseInt(new DecimalFormat("0").format(preCreateRequest.getTotalAmount() * 100)));
        order.setConsumeMoney(Integer.parseInt(new DecimalFormat("0").format(preCreateRequest.getTotalAmount() * 100)));//订单金额
        order.setNote(preCreateRequest.getWaterNote());//订单备注
        order.setStatus(0);//待支付
        //order.setActualPayment(Integer.parseInt(new DecimalFormat("0").format(preCreateRequest.getTotalAmount() * 100)));
        order.setPayType(preCreateRequest.getCodeType());//支付方式
        order.setPayWay(0);
        order.setSn(preCreateRequest.getDeviceSn());//机具sn
        Order save = orderRepository.save(order);
        AlipayTradePrecreateResponse response = this.preCreateResult(preCreateRequest);
        if (response != null) {
            if (response.isSuccess() && "10000".equals(response.getCode())) {
                save.setOutTradeNo(response.getOutTradeNo());
                orderRepository.save(save);
                Map<String, Object> map = new HashMap<>();
                map.put("qr_code", response.getQrCode());
                map.put("outTradeNo", response.getOutTradeNo());
                return new ObjectResult(CommonCode.SUCCESS, map);
            }
        }
        return new ObjectResult(CommonCode.FAIL, null);

    }


    /**
     * 预创建订单接口调用
     *
     * @param preCreateRequest
     */
    public AlipayTradePrecreateResponse preCreateResult(PreCreateRequest preCreateRequest) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("seller_id", preCreateRequest.getPId());
        map.put("total_amount", preCreateRequest.getTotalAmount());
        map.put("subject", preCreateRequest.getSubject());
        map.put("out_trade_no", PrimaryKeyUtil.nextId());
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            return response;
        } catch (AlipayApiException e) {
            LOGGER.error("预创建单异常{}", e.getMessage());
        }
        return null;
    }

    /**
     * 轮询查询订单查询接口
     * 1.轮询次数为pollingCount次，每次pollingMilliseconds秒钟
     * 2.轮询结果count次后还未付款，关闭订单
     * 3.修改订单表状态
     * 4.插入支付表
     *
     * @param outTradeNo
     * @param tradeNo
     */
    public ObjectResult queryResult(String outTradeNo, String tradeNo) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", outTradeNo);
        map.put("trade_no", tradeNo);
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        AlipayTradeQueryResponse response = null;
        Map<String, Object> responseMap = new HashMap<>();
        try {
            int count = 0;
            while (true) {
                if (count == pollingCount) {
                    //调用交易撤销接口
                    this.cancelResult(outTradeNo, tradeNo);
                    responseMap.put("status", "1");
                    responseMap.put("content", "交易撤销");
                    return new ObjectResult(CommonCode.SUCCESS, responseMap);
                }
                response = alipayClient.execute(request);
                if (response != null) {
                    if (response.isSuccess() && "10000".equals(response.getCode())) {
                        if ("WAIT_BUYER_PAY".equals(response.getTradeStatus())) {
                            Thread.sleep(pollingMilliseconds);
                            count++;
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }


        } catch (AlipayApiException e) {
            LOGGER.error("订单查询错误{}", e.getMessage());
        } catch (InterruptedException e) {
            LOGGER.error("轮询睡眠异常{}", e.getMessage());
        }
        return this.updateOrder(response, outTradeNo);
    }

    /**
     * 查询是否扫码
     *
     * @param outTradeNo
     * @param tradeNo
     * @return
     */
    public ObjectResult queryResultTwo(String outTradeNo, String tradeNo) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", outTradeNo);
        map.put("trade_no", tradeNo);
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        AlipayTradeQueryResponse response = null;
        int count = 0;
        while (true) {
            if (count == 20) {
                return new ObjectResult(CommonCode.FAIL, null);
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                LOGGER.error("是否扫码线程睡秒错误", e.getMessage());
            }
            try {
                response = alipayClient.execute(request);
                if (!"40004".equals(response.getCode())) {
                    return new ObjectResult(CommonCode.SUCCESS, null);
                }
            } catch (Exception e) {
                LOGGER.error("订单查询错误{}", e.getMessage());
            }
            count++;
        }
    }


    /**
     * 交易撤销接口
     *
     * @param outTradeNo
     * @param tradeNo
     */
    public void cancelResult(String outTradeNo, String tradeNo) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", outTradeNo);
        map.put("trade_no", tradeNo);
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        try {
            AlipayTradeCancelResponse response = alipayClient.execute(request);
            if (response != null) {
                if (response.isSuccess() && "10000".equals(response.getCode())) {
                    if ("close".equals(response.getAction())) {
                        //交易关闭

                    }
                    if ("refund".equals(response.getAction())) {
                        //已退款
                    }
                } else {

                }
            } else {

            }
        } catch (AlipayApiException e) {
            LOGGER.error("订单撤销错误{}", e.getMessage());
        }
    }

    /**
     * 更定订单状态，并保存支付表
     *
     * @param response
     * @param outTradeNo
     */
    private ObjectResult updateOrder(AlipayTradeQueryResponse response, String outTradeNo) {
        Order order = this.getByOutTradeNo(outTradeNo);
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.setCreateTime(new Date());
        orderDetails.setOrderId(order.getId());
        Pay pay = new Pay();
        pay.setCreateTime(new Date());
        pay.setOrderId(order.getId());
        pay.setMoney(order.getActualPayment());
        if (response != null) {
            if (response.isSuccess() && "10000".equals(response.getCode())) {
                if ("TRADE_SUCCESS".equals(response.getTradeStatus())) {
                    order.setStatus(1);
                    order.setOutTradeNo(response.getOutTradeNo());
                    order.setSerialNumber(response.getTradeNo());
                    order.setActualPayment(Integer.parseInt(new DecimalFormat("0").format((Double.parseDouble(response.getReceiptAmount()) * 100))));
                    pay.setStatus(1);
                    pay.setDescribe("支付成功");
                    String responseStr = JSONObject.toJSONString(response);
                    orderDetails.setContent(responseStr);
                    orderRepository.save(order);
                    payRepository.save(pay);
                    orderDetailsRepository.save(orderDetails);
                    return new ObjectResult(PayCode.PAY_SUCCESS, null);
                } else {
                    order.setStatus(2);
                    pay.setStatus(0);
                    pay.setDescribe("支付失败");
                }

                order.setSerialNumber(response.getTradeNo());
                order.setPayType("C");
                order.setPayWay(0);
                Order save = orderRepository.save(order);

                pay.setMoney(Integer.parseInt(new DecimalFormat("0").format((Double.parseDouble(response.getReceiptAmount()) * 100))));
                pay.setOrderId(save.getId());
                payRepository.save(pay);
            } else {
                pay.setOrderId(order.getId());
                pay.setStatus(0);
                pay.setDescribe("支付失败");
            }
        }
        order.setStatus(2);
        orderDetailsRepository.save(orderDetails);
        orderRepository.save(order);
        payRepository.save(pay);
        return new ObjectResult(PayCode.PAY_FILL, null);
    }

    /**
     * 1.校验参数合法性
     * 2.创建订单
     * 3.资金冻结
     */
    public ResponseResult freeze(FreezingFundRequest freezingFundRequest) {
        if (freezingFundRequest == null) {
            return new ResponseResult(CommonCode.INVALID_PARAM);
        }
        if (StringUtils.isEmpty(freezingFundRequest.getAuthCode())) {
            return new ResponseResult(CommonCode.INVALID_PARAM);
        }
        AlipayFundAuthOrderAppFreezeResponse response = this.freezeResult2(freezingFundRequest.getAuthCode(), freezingFundRequest.getOrderTitle(), freezingFundRequest.getAmount());
        if (response != null) {
            if (response.isSuccess() && "10000".equals(response.getCode())) {
                return new ResponseResult(PayCode.FREEZING_FUND_SUCCESS);
            } else {

            }
        } else {

        }
        return new ResponseResult(PayCode.FREEZING_FUND_FILL);
    }


    /**
     * 资金冻结1
     */
    private AlipayFundAuthOrderFreezeResponse freezeResult(String authCode, String orderTitle, Double amount) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayFundAuthOrderFreezeRequest request = new AlipayFundAuthOrderFreezeRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_order_no", PrimaryKeyUtil.nextId());
        map.put("out_request_no", PrimaryKeyUtil.nextId());
        map.put("auth_code", authCode);
        map.put("auth_code_type", "bar_code");
        map.put("order_title", orderTitle);
        map.put("amount", amount);
        map.put("product_code", "PRE_AUTH");
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        AlipayFundAuthOrderFreezeResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            LOGGER.error("资金冻结异常{}", e.getMessage());
        }
        return response;
    }

    /**
     * 资金冻结2
     *
     * @param authCode
     * @param orderTitle
     * @param amount
     * @return
     */
    private AlipayFundAuthOrderAppFreezeResponse freezeResult2(String authCode, String orderTitle, Double amount) {
        String charset = "GBK";
        String sign_type = "RSA2";
        AlipayClient alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", charset, alipayPublicKey, sign_type);
        AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
        Map<String, Object> map = new HashMap<>();
        map.put("out_order_no", PrimaryKeyUtil.nextId());
        map.put("out_request_no", PrimaryKeyUtil.nextId());
        //map.put("auth_code",authCode);
        map.put("order_title", orderTitle);
        map.put("amount", amount);
        map.put("product_code", "PRE_AUTH_ONLINE");
        String mapStrJson = JSONObject.toJSONString(map);
        request.setBizContent(mapStrJson);
        AlipayFundAuthOrderAppFreezeResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            LOGGER.error("资金冻结异常{}", e.getMessage());
        }
        return response;
    }

    /**
     * 根据id获取订单
     *
     * @param id
     * @return
     */
    private Order getById(String id) {
        Optional<Order> optional = orderRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 根据外部订单号查询
     *
     * @param outTradeNo
     * @return
     */
    private Order getByOutTradeNo(String outTradeNo) {
        Order order = orderRepository.findByOutTradeNo(outTradeNo);
        if (order == null) {
            ExceptionCast.cast(CommonCode.SERVER_ERROR);
        }
        return order;
    }



}
